package com.uduemc.biso.node.module.common.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.common.entities.publishdata.DataBody;
import com.uduemc.biso.node.module.common.service.CPublishService;

@RestController
@RequestMapping("/common/publish")
public class CPublishController {

	private static final Logger logger = LoggerFactory.getLogger(CPublishController.class);

	@Autowired
	private CPublishService cPublishServiceImpl;

	/**
	 * 保存当前页面编辑的组件数据
	 * 
	 * @param dataBody
	 * @param errors
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@PostMapping("/save")
	public RestResult save(@Valid @RequestBody DataBody dataBody, BindingResult errors)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		logger.info(dataBody.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}
			return RestResult.error(message);
		}

		boolean save = false;
		try {
			save = cPublishServiceImpl.save(dataBody);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}

		return RestResult.ok(save ? 1 : 0, Integer.class.toString());
	}
}
